<?php

class LocaleHelper {
	public $locale;
	public $country;
	public $lang;
	private $defaultLocale = 'en_US';
	
	public function __construct() {
		if (isset($_SESSION) && isset($_SESSION["user_id"])) {
			$u = new InsightUser();
			$this->setLocale($u->locale);
		}
	}
	
	public function setLocale($locale) {
		$this->locale = $locale;

		if (!isset($this->locale)) $this->locale = $this->defaultLocale;

		if (stripos($this->locale, '_') !== false) {
			list($this->lang, $this->country) = explode('_', $this->locale, 2);
		} else {
			$this->lang = $this->locale;
		}
	}
	
	public function parse($dateStr) {
		exec("locale -a", $locales);
		$locales = array_merge(array(NULL, "en", "de", "fr", "nl", "pt"), $locales);

		$iso = null;
		foreach ($locales as $l) {
			$iso = $this->translate($dateStr, $l);
			if (isset($iso)) return $iso;
		}
		
		return LocaleHelper::now();
	}
	
	public function translate($dateStr, $locale=null) {
		$current_locale;
		if ($locale != null) {
			$current_locale = setlocale(LC_TIME, 0);
			setlocale(LC_TIME, $locale, $locale.".UTF-8", $locale.".utf8");
		}
		
		$iso = null;
		for ($i=0; $i<count($this->dateFormats); $i++) {
			$dateStr = str_replace(" de", "", $dateStr);
			$dateParts = strptime($dateStr, $this->dateFormats[$i]);
			if ($dateParts !== false) {
				$time = mktime(
					$hour = $dateParts['tm_hour'],
					$minute = $dateParts['tm_min'],
					$second = 0,
					$month = $dateParts['tm_mon']+1,
					$day = $dateParts['tm_mday'],
					$year = $dateParts['tm_year']+1900
				);
				$iso = strftime(LocaleHelper::$universal, $time);
				break;
			}
		}

		if (isset($current_locale)) setlocale(LC_TIME, $current_locale); // reset
		
		return $iso;
	}
	
	public static function now() {
		return strftime(LocaleHelper::$universal, time());
	}
	
	// Defines Date formats shown in Gmail by locale
	// Defines a default for a language and a locale-specific instances where possible
	private $dateFormats = array(
		'%a, %b %e, %Y at %l:%M %p', // Thu, Sep 8, 2011 at 3:29 PM
		'%a, %b %e, %Y at %H:%M', // Tue, Oct 11, 2011 at 21:43
		'%e %B %Y %H:%M', // 13 septembre 2011 12:25
		'%e. %B %Y %H:%M' // 13. September 2011 09:34
	);
	
	private static $universal = '%Y-%m-%dT%H:%M:%S';
}

?>